package config

import (
	"db-sharding/system/redis"
	"github.com/siddontang/go-yaml/yaml"
	"io/ioutil"
)

type NodeConfig struct {
	Name             string `yaml:"name"`
	DownAfterNoAlive int    `yaml:"down_after_noalive"`
	IdleConns        int    `yaml:"idle_conns"`
	RWSplit          bool   `yaml:"rw_split"`

	User         string `yaml:"user"`
	Password     string `yaml:"password"`
	DbName       string `yaml:"dbName"`
	ProxyLotCode string `yaml:"proxy_lotcode"`

	Master string `yaml:"master"`
	Slave  string `yaml:"slave"`
}

type SchemaConfig struct {
	DB          string      `yaml:"db"`
	Nodes       []string    `yaml:"nodes"`
	RulesConifg RulesConfig `yaml:"rules"`
}

type RulesConfig struct {
	Default   string        `yaml:"default"`
	ShardRule []ShardConfig `yaml:"shard"`
}

type ShardConfig struct {
	Table string   `yaml:"table"`
	Key   string   `yaml:"key"`
	Nodes []string `yaml:"nodes"`
	Type  string   `yaml:"type"`
	Range string   `yaml:"range"`
}

//网络代理配置
type ProxyConfig struct {
	Enable               bool   `yaml:"enable"`                  //开关
	NginxConfPath        string `yaml:"nginx_conf_path"`         //ng配置
	NginxReloadShellPath string `yaml:"nginx_reload_shell_path"` //能刷新shell脚本路径
}

type Config struct {
	Addr     string       `yaml:"addr"`
	User     string       `yaml:"user"`
	Password string       `yaml:"password"`
	Proxy    *ProxyConfig `yaml:"network_proxy"`

	Nodes *[]NodeConfig `yaml:"nodes"`

	Schemas *[]SchemaConfig `yaml:"schemas"`

	Redis *redis.RedisConfig `yaml:"redis"`
}

var GlobalCfg *Config

func ParseConfigData(data []byte) error {
	GlobalCfg = &Config{}
	if err := yaml.Unmarshal(data, GlobalCfg); err != nil {
		return err
	}
	return nil
}

func ParseConfigFile(fileName string) error {
	data, err := ioutil.ReadFile(fileName)
	if err != nil {
		return err
	}

	return ParseConfigData(data)
}
